#include "code_window.h"
#include "ui_code_window.h"

#include <Qsci/qsciscintilla.h>

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>

code_window::code_window(QString module_name, Module_Code *code, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::code_window)
{
    ui->setupUi(this);

    setWindowTitle("Code Window");
    setAttribute(Qt::WA_ShowModal, true);   // 设置模态窗口
    setAttribute(Qt::WA_DeleteOnClose);     // 关闭窗口时触发析构函数

    this->code = code;
    this->module_name = module_name;

    this->init_Qsci();


}

code_window::~code_window()
{
    delete ui;
}

void code_window::init_Qsci()
{
    /// Code Edit
    code_edit_editext->setLexer(code_edit_textLexer);

    code_edit_editext->setMarginType(0, QsciScintilla::NumberMargin);
    code_edit_editext->setMarginLineNumbers(0, true);
    code_edit_editext->setMarginWidth(0, 30);

    connect(code_edit_editext, &QsciScintilla::textChanged, this, &code_window::code_edit_textChanged);

    ui->gridLayout_code_edit->addWidget(code_edit_editext);

    code_edit_editext->setText(this->code->user_code);
    ///---------------------------------------------------------------

    /// Code View
    code_view_editext->setLexer(code_view_textLexer);

    code_view_editext->setMarginType(0, QsciScintilla::NumberMargin);
    code_view_editext->setMarginLineNumbers(0, true);
    code_view_editext->setMarginWidth(0, 30);

    code_view_editext->setReadOnly(true);   // 设置只读模式

    this->make_codeView_code();

    ui->gridLayout_code_view->addWidget(code_view_editext);



    ///---------------------------------------------------------------
}

void code_window::make_codeView_code()
{
    code_view_editext->clear();

    code_view_editext->append(QString("module %1()\n").arg(this->module_name));

    code_view_editext->append(this->code->module_code + "\n");//代码前半段

    code_view_editext->append("// 用户代码\n");
    code_view_editext->append(this->code->user_code + "\n\n");


    code_view_editext->append("endmodule");//代码后半段
}


void code_window::on_tabWidget_currentChanged(int index)
{//切换编辑/显示界面时自动保存代码
    if (index == 1)
        this->make_codeView_code();
}

void code_window::code_edit_textChanged()
{
    this->code->user_code = this->code_edit_editext->text();
}

